﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Net_SCADA
{
    public class Ini
    {
        // 声明INI文件的写操作函数 WritePrivateProfileString()


        [System.Runtime.InteropServices.DllImport("kernel32")]

        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);

        // 声明INI文件的读操作函数 GetPrivateProfileString()  

        [System.Runtime.InteropServices.DllImport("kernel32")]
        private extern static int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);
        [System.Runtime.InteropServices.DllImport("kernel32")]

        static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);
        [System.Runtime.InteropServices.DllImport("kernel32")]

        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


        //public static string sPath = FileHelper.GetFullName("bellinfo.ini");  

        private string _filename;

        //public static string sPath = System.Windows.Forms.Application.StartupPath + "\\test.ini";
        public Ini() { }
        public Ini(string filename)
        {
            this.Filename = filename;
        }


        public string Filename
        {
            get { return _filename; }
            set
            {
                FileInfo file = new FileInfo(value);
                if ((!file.Exists))
                {
                    //文件不存在，建立文件 
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(value);
                    try
                    {
                        sw.Write("[CreatIni]");
                        sw.Close();
                    }
                    catch
                    {
                        throw (new ApplicationException("Ini文件不存在"));
                    }
                }
                _filename = file.FullName;
            }
        }
        /// <summary>
        /// 写某个键的值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径  
            WritePrivateProfileString(section, key, value, _filename);
        }
        /// <summary>
        /// 获取一个section下的所有的键名称。
        /// </summary>
        /// <param name="section"></param>
        /// <returns></returns>
        public List<StringBuilder> GetKeys(string section)
        {
            byte[] buffer = new byte[2048];
            GetPrivateProfileSection(section, buffer, 2048, _filename);
            String[] tmp = Encoding.ASCII.GetString(buffer).Trim('\0').Split('\0');
            List<StringBuilder> result = new List<StringBuilder>();
            foreach (String entry in tmp)
            {
                result.Add(new StringBuilder().Append(entry.Substring(0, entry.IndexOf("="))));
            }
            return result;
        }

        public bool DeleteKey(string section, string key)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException("必须指定节点名称", "section");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("必须指定键名称", "key");
            }

            return WritePrivateProfileString(section, key, null, _filename);
        }

        /// <summary>
        /// 读取某个键的值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节  
            StringBuilder temp = new StringBuilder(1024);
            //string temp=new string(new char[1024]);
            // section=配置节，key=键名，temp=上面，path=路径  
            GetPrivateProfileString(section, key, "", temp, 1024, _filename);
            return temp.ToString();

        }
    }
}
